import { createSlice, createAsyncThunk, PayloadAction } from "@reduxjs/toolkit";
import { ProductSearch } from "../../Utils/Http";
interface StateProps {
  loading: boolean;
  error: string | null;
  data: any;
  pagination: any;
}

const initialState: StateProps = {
  loading: true,
  error: null,
  data: null,
  pagination: null,
};

export const searchProduct = createAsyncThunk(
  "productSearch/getProductSearch",
  async (
    params: {
      keyword?: string | any;
      nextPage: number | string;
      pageSize: number | string;
    },
    thunkAPI
  ) => {
    const res = await ProductSearch(
      params.keyword,
      params.nextPage,
      params.pageSize
    );
    return res;
  }
);

export const searchSlice = createSlice({
  name: "searchProduct",
  initialState,
  reducers: {},
  extraReducers: {
    [searchProduct.pending.type]: (state, action) => {
      state.loading = true;
    },
    [searchProduct.fulfilled.type]: (state, action) => {
      state.loading = false;
      state.error = null;
      state.data = action.payload.data;
      state.pagination = action.payload.pagination;
    },
    [searchProduct.rejected.type]: (state, action: PayloadAction<string>) => {
      state.loading = false;
      state.error = action.payload;
    },
  },
});
